package com.ruoyi.web.controller.net;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.net.domain.ElementPortEth;
import com.ruoyi.net.domain.ElementPortEthSub;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.Device;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.domain.ElementPortTrunk;
import com.ruoyi.net.service.IElementPortTrunkService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 网元-接口-trunk主接口Controller
 * 
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-接口-trunk主接口")
@RestController
@RequestMapping("/element/port/trunk")
public class ElementPortTrunkController extends BaseController {
    @Autowired
    private IElementPortTrunkService elementPortTrunkService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 读取网元-接口-trunk主接口列表
     */
    @ApiOperation(value = "读取网元-接口-trunk主接口列表", httpMethod = "GET")
    @GetMapping("/read")
    public TableDataInfo read(ElementPortTrunk elementPortTrunk) {
        List<ElementPortTrunk> elementPortTrunks = new ArrayList<>();
        StringBuilder xml = new StringBuilder();
        xml.append(
                "<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "    <interfaces>" +
                        "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                        "        <type>ETH-LAG</type>" + // trunk接口
//                        "        <enabled>enable</enabled>" +
                        "      </interface>" +
                        "    </interfaces>" +
                        "  </if>");
        NetElement netElement = netElementService.getCacheObject(elementPortTrunk.getElementId());
        if (sysConfigService.selectDebugEnabled()) {
            deviceManager.getDevice(netElement.getIp());
            String rpcReply = deviceManager.getConfig(xml.toString());

            // 解析xml
            NodeList list = findNetConfXmlNodes(rpcReply, "//interfaces/interface");
            if (list != null && list.getLength() > 0) {
                for (int i = 0; i < list.getLength(); i++) {
                    ElementPortTrunk entity = new ElementPortTrunk();
                    Node node = list.item(i);
                    // 通过标签名获取节点的值
                    entity.setTerminalName(getXmlLabelValue(node, "name"));
//                    entity.setTerminalEnable(getXmlLabelValue(node, "enabled"));
                    entity.setPortDesc(getXmlLabelValue(node, "description"));
                    Node ethlagInterface = getXmlLabelNode(node, "ethlag-interface");
                    entity.setLagMode(getXmlLabelValue(ethlagInterface, "lag-mode"));
                    entity.setReturnType(getXmlLabelValue(ethlagInterface, "lag-return-mode"));
                    entity.setWaitMinute(getXmlLabelValue(ethlagInterface, "lag-recover-time"));
                    entity.setMaxMembers(getXmlLabelValue(ethlagInterface, "max-active-numbers"));
                    entity.setMinMembers(getXmlLabelValue(ethlagInterface, "min-active-numbers"));
                    // todo 多个怎么处理？
                    Node lagInterface = getXmlLabelNode(ethlagInterface, "lag-add-interface-cfg");
                    entity.setMemberPort(getXmlLabelValue(lagInterface, "eth-ifname"));
                    entity.setMemberRole(getXmlLabelValue(lagInterface, "lag-member-role"));
                    entity.setTerminalMode(getXmlLabelValue(node, "transport-layer"));
                    entity.setMbps(getXmlLabelValue(node, "bandwidth"));
                    Node ipNode = getXmlLabelNode(node, "ip");
                    entity.setMaxFrameLen(getXmlLabelValue(ipNode, "ipv4-mtu"));
                    Node ipv4AddressListNode = getXmlLabelNode(ipNode, "ipv4-address-list");
                    if (ipv4AddressListNode != null) {
                        String ip = getXmlLabelValue(ipv4AddressListNode, "ipv4-address");
                        entity.setIp(StringUtils.isNotEmpty(ip) ? ip.split("/")[0] : "");
                        entity.setMask(StringUtils.isNotEmpty(ip) ? ip.split("/")[1] : "");
//                        entity.setIpForm(getXmlLabelValue(ipv4AddressListNode, "secondry-use"));
                    }
                    Node switchVlan = getXmlLabelNode(node, "switched-vlan-cfg");
                    Node switchedNode = getXmlLabelNode(switchVlan, "switched-tpids");
                    entity.setVlan(getXmlLabelValue(switchedNode, "outer-tpid"));
                    entity.setStatus("1"); // 从设备读取到的配置，设置状态为激活

                    elementPortTrunks.add(entity);
                }
            }
        }
        startPage();
        return getDIYPageTable(elementPortTrunks);
    }

    /**
     * 查询网元-接口-trunk主接口列表
     */
    @ApiOperation(value = "查询网元-接口-trunk主接口列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:trunk:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementPortTrunk elementPortTrunk) {
        startPage();
        List<ElementPortTrunk> list = elementPortTrunkService.selectElementPortTrunkList(elementPortTrunk);
        return getDataTable(list);
    }

    /**
     * 导出网元-接口-trunk主接口列表
     */
    @ApiOperation(value = "导出网元-接口-trunk主接口列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:trunk:export')")
    @Log(title = "网元-接口-trunk主接口", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementPortTrunk elementPortTrunk) {
        List<ElementPortTrunk> list = elementPortTrunkService.selectElementPortTrunkList(elementPortTrunk);
        ExcelUtil<ElementPortTrunk> util = new ExcelUtil<ElementPortTrunk>(ElementPortTrunk.class);
        util.exportExcel(response, list, "网元-接口-trunk主接口数据");
    }

    /**
     * 获取网元-接口-trunk主接口详细信息
     */
    @ApiOperation(value = "获取网元-接口-trunk主接口详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:trunk:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementPortTrunkService.selectElementPortTrunkById(id));
    }

    /**
     * 新增网元-接口-trunk主接口
     */
    @ApiOperation(value = "新增网元-接口-trunk主接口", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:trunk:add')")
    @Log(title = "网元-接口-trunk主接口", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementPortTrunk elementPortTrunk) {
        return toAjax(elementPortTrunkService.insertElementPortTrunk(elementPortTrunk));
    }

    /**
     * 修改网元-接口-trunk主接口
     */
    @ApiOperation(value = "修改网元-接口-trunk主接口", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:trunk:edit')")
    @Log(title = "网元-接口-trunk主接口", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementPortTrunk elementPortTrunk) {
        return toAjax(elementPortTrunkService.updateElementPortTrunk(elementPortTrunk));
    }

    /**
     * 删除网元-接口-trunk主接口
     */
    @ApiOperation(value = "删除网元-接口-trunk主接口", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:trunk:remove')")
    @Log(title = "网元-接口-trunk主接口", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementPortTrunkService.deleteElementPortTrunkByIds(ids));
    }

    /**
     * 激活设备
     *
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/activate/{id}")
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementPortTrunk entity = elementPortTrunkService.selectElementPortTrunkById(id);
        entity.setStatus("1");
        if (sendXml(entity)) {
            return toAjax(elementPortTrunkService.updateElementPortTrunk(entity));
        } else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     *
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementPortTrunk entity = elementPortTrunkService.selectElementPortTrunkById(id);
        entity.setStatus("0");
        if (sendXml(entity)) {
            return toAjax(elementPortTrunkService.updateElementPortTrunk(entity));
        } else {
            return AjaxResult.error("去激活设备失败");
        }
    }

    private boolean sendXml(ElementPortTrunk entity) {
        boolean isSend = false;
        // TODO: 2024/11/29 设备联调
        NetElement netElement = netElementService.getCacheObject(entity.getElementId());
        Device device = deviceManager.getDevice(netElement.getIp());
        if (device.isConnected()) {
            StringBuilder xml = new StringBuilder();
            if ("1".equalsIgnoreCase(entity.getStatus())) {
                xml.append("<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "    <interfaces>" +
                        "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                        "        <name>lag" + entity.getLagId() + "</name>" +
                        "        <type>ETH-LAG</type>");
                if (StringUtils.isNotEmpty(entity.getPortDesc())) {
                    xml.append("        <description>" + entity.getPortDesc() + "</description>");
                }
                xml.append("        <enabled>enable</enabled>" +
                        "        <ethlag-interface xmlns=\"http://fiberhome.com/fhnw/yang/interface/ethinterface/fos-ethif-lag\">");
                if (StringUtils.isNotEmpty(entity.getSystemLevel())) {
                    xml.append("          <lag-arithmetic>" + entity.getSystemLevel() + "</lag-arithmetic>");  // 负载分担算法
                }
                if (StringUtils.isNotEmpty(entity.getLagMode())) {
                    xml.append("          <lag-mode>" + entity.getLagMode() + "</lag-mode>");
                }
//                    "          <lag-return-mode>" + entity.getReturnType() + "</lag-return-mode>" +
                if (StringUtils.isNotEmpty(entity.getWaitMinute())) {
                    xml.append("          <lag-recover-time>" + entity.getWaitMinute() + "</lag-recover-time>");
                }
                if (StringUtils.isNotEmpty(entity.getMaxMembers())) {
                    xml.append("          <max-active-numbers>" + entity.getMaxMembers() + "</max-active-numbers>");
                }
                if (StringUtils.isNotEmpty(entity.getMinMembers())) {
                    xml.append("          <min-active-numbers>" + entity.getMinMembers() + "</min-active-numbers>");
                }
                if (StringUtils.isNotEmpty(entity.getMemberPort())) {
                    String[] members = entity.getMemberPort().split(",");
                    for (String member : members) {
//                成员口角色设置
                        xml.append("          <lag-add-interface-cfg>")
                                .append("            <eth-ifname>")
                                .append(member).append("</eth-ifname>");
                        /*if (StringUtils.isNotEmpty(entity.getMemberRole())) {
                            xml.append("            <lag-member-role>")
                                    .append(entity.getMemberRole())
                                    .append("</lag-member-role>");
                        }*/
                        xml.append("          </lag-add-interface-cfg>");
                    }
                }
                xml.append("        </ethlag-interface>");
                if (StringUtils.isNotEmpty(entity.getTerminalMode())) {
                    xml.append("        <transport-layer xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-l2l3common\">" + entity.getTerminalMode() + "</transport-layer>");
//                    "        <bandwidth xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-l2l3common\">" + entity.getMbps() + "</bandwidth>" +
                }
                xml.append("        <ip xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-l2l3common\">" +
                        "           <ipv4-mtu>" + (StringUtils.isEmpty(entity.getMaxFrameLen()) ? "1500" : entity.getMaxFrameLen()) + "</ipv4-mtu>");
                if (StringUtils.isNotEmpty(entity.getIp()) && StringUtils.isNotEmpty(entity.getMask())) {
                    xml.append("           <ipv4-address-list>" +
                            "               <ipv4-address>" + entity.getIp() + "/" + entity.getMask() + "</ipv4-address>" +
                            "               <secondry-use>mast</secondry-use>" +
                            "           </ipv4-address-list>");
                }
                xml.append("        </ip>" +
                        "        <qos-policy-cfgs xmlns=\"http://fiberhome.com/fhnw/yang/qos/fos-qos\"/>" +
                        // todo 2025-02-05 测验收比对，暂时注释
                            /*"        <switched-vlan-cfg xmlns=\"http://fiberhome.com/fhnw/yang/ethernetservice/fos-vlan\">" +
                    "          <switched-tpids>" +
                    "            <outer-tpid>" + ("enable".equalsIgnoreCase(entity.getVlanEnable()) || "1".equalsIgnoreCase(entity.getVlanEnable()) ? entity.getVlan() : "") + "</outer-tpid>" +
                    "          </switched-tpids>" +
                    "        </switched-vlan-cfg>" +*/
                        "      </interface>" +
                        "    </interfaces>" +
                        "  </if>");
            } else {
                // 去激活
                xml.append("<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "    <interfaces>" +
                        "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                        "        <name>lag" + entity.getLagId() + "</name>" +
                        "        <type>ETH-LAG</type>");
                xml.append(
                        "        <ethlag-interface xmlns=\"http://fiberhome.com/fhnw/yang/interface/ethinterface/fos-ethif-lag\">");
                if (StringUtils.isNotEmpty(entity.getMemberPort())) {
                    String[] members = entity.getMemberPort().split(",");
                    for (String member : members) {
//                成员口角色设置
                        xml.append("          <lag-add-interface-cfg nc:operation=\"remove\">")
                                .append("            <eth-ifname>")
                                .append(member).append("</eth-ifname>");
                        xml.append("          </lag-add-interface-cfg>");
                    }
                }
                xml.append("        </ethlag-interface>" +
                        "      </interface>" +
                        "    </interfaces>" +
                        "  </if>");
                xml.append("<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "    <interfaces>" +
                        "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\" nc:operation=\"remove\">" +
                        "        <name>lag" + entity.getLagId() + "</name>" +
                        "        <type>ETH-LAG</type>" +
                        "      </interface>" +
                        "    </interfaces>" +
                        "  </if>");

            }
            logger.info("trunk主接口激活xml：" + xml);
            isSend = deviceManager.editConfig(xml.toString(), "merge");
        }
        return isSend;
    }
}